package com.dev.widget.ui;


import com.dev.base.widget.BaseImageView;
import com.dev.utils.LogUtils;
import com.dev.utils.app.SizeUtils;
import dev.widget.ResourceTable;
import ohos.agp.components.*;
import ohos.agp.render.*;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.ResourceManager;
import ohos.global.resource.WrongTypeException;

import java.io.IOException;
import java.util.Optional;

/**
 * detail: 自定义角标 View
 *
 * @author Ttt
 * <pre>
 *     <p></p>
 *     app:dev_paddingTop=""
 *     app:dev_paddingCenter=""
 *     app:dev_paddingBottom=""
 *     app:dev_fillColor=""
 *     app:dev_flags=""
 *     <p></p>
 *     app:dev_text1=""
 *     app:dev_textColor1=""
 *     app:dev_textHeight1=""
 *     app:dev_textBold1=""
 *     <p></p>
 *     app:dev_text2=""
 *     app:dev_textColor2=""
 *     app:dev_textHeight2=""
 *     app:dev_textBold2=""
 * </pre>
 */
public class CornerLabelView extends Component {

    private final static String TAG = "CornerLabelView";

    private ResourceManager resourceManager;

    // 三角形斜边长
    private static final float SQRT2 = (float) Math.sqrt(2);
    // 内部画笔
    private Paint mPaint;
    // Text1 Paint
    private final Painter mText1 = new Painter();
    // Text2 Paint
    private final Painter mText2 = new Painter();
    // 顶部边距
    private float mPaddingTop = 0;
    // Text1、Text2 边距
    private float mPaddingCenter = 0;
    // 底部边距
    private float mPaddingBottom = 0;
    // 是否左边显示角标
    private boolean mIsLeft = true;
    // 是否顶部显示角标
    private boolean mIsTop = true;
    // 是否角标三角形铺满样式
    private boolean mIsTriangle = true;
    //图片控件
    private BaseImageView image3;
    // 当前 View 高度
    private int mHeight;
    //点击改变进行适配的 boolean
    private boolean isClickTriangle = false;

    public CornerLabelView(Context context) throws NotExistException, WrongTypeException, IOException {
        super(context);
        initAttrs(context, null);
    }

    public CornerLabelView(Context context, AttrSet attrSet) throws NotExistException, WrongTypeException, IOException {
        super(context, attrSet);
        initAttrs(context, attrSet);
    }

    public CornerLabelView(Context context, AttrSet attrSet, String styleName) throws NotExistException, WrongTypeException, IOException {
        super(context, attrSet, styleName);
        initAttrs(context, attrSet);
    }

    public CornerLabelView(Context context, AttrSet attrSet, int resId) throws NotExistException, WrongTypeException, IOException {
        super(context, attrSet, resId);
        initAttrs(context, attrSet);
    }

    private int leftMargin = 252;
    private int topMargin = 252;

    /**
     * 初始化
     *
     * @param context {@link Context}
     * @param attrs   {@link AttrSet}
     */
    private void initAttrs(
            Context context,
            AttrSet attrs
    ) throws NotExistException, WrongTypeException, IOException {
        LogUtils.error(TAG, "initAttrs");
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.FILL_STYLE);
        mPaint.setBlendMode(BlendMode.SRC_OVER);
        mPaint.setAntiAlias(true);
        resourceManager = getResourceManager();
        if (context != null && attrs != null) {
            // TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DevWidget);

            mPaddingTop = getDimension(attrs.getAttr(resourceManager.getElement(ResourceTable.String_dev_paddingTop).getString()), SizeUtils.dipConvertPx(30));
            mPaddingCenter = getDimension(attrs.getAttr(resourceManager.getElement(ResourceTable.String_dev_paddingCenter).getString()), 0);
            mPaddingBottom = getDimension(attrs.getAttr(resourceManager.getElement(ResourceTable.String_dev_paddingBottom).getString()), SizeUtils.dipConvertPx(10));

            mText1.text = getString(attrs.getAttr(resourceManager.getElement(ResourceTable.String_dev_text1).getString()), "");
            LogUtils.error(TAG, "mText.text" + mText1.getText());
            mText1.textColor = getColor(attrs.getAttr(resourceManager.getElement(ResourceTable.String_dev_textColor1).getString()), new Color(0xffffffff));
            mText1.textHeight = getDimension(attrs.getAttr(resourceManager.getElement(ResourceTable.String_dev_textHeight1).getString()), SizeUtils.dipConvertPx(40));
            mText1.textBold = getBoolean(attrs.getAttr(resourceManager.getElement(ResourceTable.String_dev_textBold1).getString()), false);
            mText1.init();

            mText2.text = getString(attrs.getAttr(resourceManager.getElement(ResourceTable.String_dev_text2).getString()), "");
            mText2.textColor = getColor(attrs.getAttr(resourceManager.getElement(ResourceTable.String_dev_textColor2).getString()), new Color(0x66ffffff));
            mText2.textHeight = getDimension(attrs.getAttr(resourceManager.getElement(ResourceTable.String_dev_textHeight2).getString()), SizeUtils.dipConvertPx(20));
            mText2.textBold = getBoolean(attrs.getAttr(resourceManager.getElement(ResourceTable.String_dev_textBold2).getString()), false);
            mText2.init();


            Color fillColor = getColor(attrs.getAttr(resourceManager.getElement(ResourceTable.String_dev_fillColor).getString()), new Color(66000000));
            int flags = getInteger(attrs.getAttr(resourceManager.getElement(ResourceTable.String_dev_flags).getString()), 0);

            mIsLeft = (flags & 1) == 0;
            mIsTop = (flags & 2) == 0;
            mIsTriangle = (flags & 4) > 0;
            LogUtils.error(TAG, "fillColor" + fillColor.getValue());
            mPaint.setColor(fillColor);
        }


        //测量
        this.mHeight = (int) (mPaddingTop + mPaddingCenter + mPaddingBottom
                + mText1.textHeight + mText2.textHeight);
        LogUtils.error(TAG, "mHeight =" + mHeight);
       /* int size = (int) (mHeight * SQRT2);
        setComponentSize(size, size);*/


        addDrawTask(new DrawTask() {
            @Override
            public void onDraw(Component component, Canvas canvas) {
                float xy = mHeight / SQRT2;
                canvas.save();
                canvas.translate(xy, xy);
                canvas.rotate((mIsTop ? 1 : -1) * (mIsLeft ? -45 : 45), 0, 0);
                if (!mIsLeft) {
                    LogUtils.error(TAG, "height = " + mHeight + " temp = " + (mHeight - 120f) / 120f);
                    // int leftMargin = (int) ((1.0f - (mHeight - 120f) /120f)* 252f);
                    if (image3 != null) {
                        leftMargin = image3.getWidth() - (int) (150f * mHeight / 106f);
                    } else {
                        leftMargin = 400 - (int) (150f * mHeight / 106f);
                    }
                    LogUtils.error(TAG, "leftMarigin = " + leftMargin);
                    setLeftMargin();
                }
                if (!mIsTop) {
                    if (image3 !=null) {
                        topMargin = image3.getHeight() - (int) (150f * mHeight / 106f);
                    }else {
                        topMargin = 400 - (int) (150f * mHeight / 106f);
                    }
                    setTopMargin();
                }
                canvas.drawPath(calcPath(), mPaint);


               /* canvas.drawPath(calcPath1(), mPaint);
                float xy = mHeight / SQRT2;
                canvas.translate(xy, xy);
                canvas.rotate((mIsTop ? 1 : -1) * (mIsLeft ? -45 : 45), 0, 0);*/

                if (mIsTriangle) {
                    if (isClickTriangle) {
                        mText1.draw2(canvas, mPaddingBottom, mIsTop);
                    } else {
                        mText1.draw1(canvas, mPaddingBottom, mIsTop);
                    }
                    mText2.draw2(canvas, mPaddingBottom + mPaddingCenter + mText1.textHeight, mIsTop);
                } else {
                    mText1.draw2(canvas, mPaddingBottom, mIsTop);
                }
                canvas.restore();
            }
        });
    }

    private int getDimension(Optional<Attr> attr, int defaultValue) {
        //isPresent = false 表示不存在返回默认  = true 表示有输入，使用输入的数据为
        if (attr.isPresent()) {
            return attr.get().getIntegerValue();
        } else {
            return defaultValue;
        }
    }

    private String getString(Optional<Attr> attr, String defaultValue) {
        if (attr.isPresent()) {
            return attr.get().getStringValue();
        } else {
            return defaultValue;
        }
    }

    private int getInteger(Optional<Attr> attr, int defaultValue) {
        if (attr.isPresent()) {
            return attr.get().getIntegerValue();
        } else {
            return defaultValue;
        }
    }

    private Color getColor(Optional<Attr> attr, Color defaultValue) {
        if (attr.isPresent()) {
            return attr.get().getColorValue();
        } else {
            return defaultValue;
        }
    }

    private boolean getBoolean(Optional<Attr> attr, boolean defaultValue) {
        //isPresent = false 表示不存在返回默认  = true 表示有输入，使用输入的数据为
        if (attr.isPresent()) {
            return attr.get().getBoolValue();
        } else {
            return defaultValue;
        }
    }


    /**
     * 计算路径
     *
     * @return {@link Path}
     */
    private Path calcPath() {
        Path path = new Path();
        path.moveTo(-mHeight, 0);
        path.lineTo(mHeight, 0);
        int factor = mIsTop ? -1 : 1;
        if (mIsTriangle) {
            path.lineTo(0, factor * mHeight);
        } else {
            int lineHeight = factor * (int) (mPaddingCenter + mPaddingBottom + mText1.textHeight);
            if (mIsTop) {
                path.lineTo(mHeight + lineHeight, lineHeight);
                path.lineTo(-mHeight + lineHeight, lineHeight);
            } else if (mIsLeft) {
                path.lineTo(mHeight - lineHeight, lineHeight);
                path.lineTo(-mHeight - lineHeight, lineHeight);
            } else {
                path.lineTo(mHeight - lineHeight, lineHeight);
                path.lineTo(-mHeight + lineHeight, lineHeight);
            }
            //当前状态是 mIsTriangle 是false
        }
        path.close();
        return path;
    }

    /**
     * 计算路径
     *
     * @return {@link Path}
     */
    private Path calcPath1() {
        //当前状态是三角形
        if (mIsTriangle) {
            Path path = new Path();
            int count = (int) (mHeight + mText1.offset * 2 + mText2.offset * 2);
            if (mIsTop) {
                if (mIsLeft) {
                    path.moveTo(0, 0);
                    path.lineTo(count, 0);
                    path.lineTo(0, count);
                    path.close();
                    return path;
                } else {
                    LogUtils.error(TAG, " mIsLeft:" + getWidth());
                    path.moveTo(count, 0);
                    path.lineTo(-count, 0);
                    path.lineTo(count, count);
                    path.close();
                    return path;
                }
            } else {

            }
        } else {

        }
        return null;
    }


    // ===============
    // = 对外公开方法 =
    // ===============

    /**
     * 获取 Text1 Painter
     *
     * @return {@link Painter}
     */
    public Painter getPainter1() {
        return mText1;
    }

    /**
     * 获取 Text2 Painter
     *
     * @return {@link Painter}
     */
    public Painter getPainter2() {
        return mText2;
    }

    // =

    /**
     * 设置顶部边距
     *
     * @param px 边距值 ( px )
     * @return {@link CornerLabelView}
     */
    public CornerLabelView setPaddingTop1(float px) {
        this.mPaddingTop = px;
        postLayout();
        invalidate();
        return this;
    }

    /**
     * 设置 Text1、Text2 边距
     *
     * @param px 边距值 ( px )
     * @return {@link CornerLabelView}
     */
    public CornerLabelView setPaddingCenter(float px) {
        this.mPaddingCenter = px;
        postLayout();
        invalidate();
        return this;
    }

    /**
     * 设置底部边距
     *
     * @param px 边距值 ( px )
     * @return {@link CornerLabelView}
     */
    public CornerLabelView setPaddingBottom1(float px) {
        this.mPaddingBottom = px;
        this.mHeight = (int) (mPaddingTop + mPaddingCenter + mPaddingBottom
                + mText1.textHeight + mText2.textHeight);
        postLayout();
        invalidate();
        return this;
    }

    /**
     * 设置背景填充颜色
     *
     * @param color Color
     * @return {@link CornerLabelView}
     */
    public CornerLabelView setFillColor(int color) {
        this.mPaint.setColor(new Color(color));
        invalidate();
        return this;
    }

    /**
     * 设置背景填充渐变色
     *
     * @param shader {@link Shader}
     * @return {@link CornerLabelView}
     */
    public CornerLabelView setFillShader(Shader shader) {
        this.mPaint.setShader(shader, Paint.ShaderType.LINEAR_SHADER);
        invalidate();
        return this;
    }

    /**
     * 设置左边显示角标
     *
     * @return {@link CornerLabelView}
     */
    public CornerLabelView left() {
        this.mIsLeft = true;
        invalidate();
        return this;
    }

    /**
     * 设置右边显示角标
     *
     * @return {@link CornerLabelView}
     */
    public CornerLabelView right(BaseImageView test) {
        this.mIsLeft = false;
        image3 = test;
        invalidate();
        return this;
    }

    /**
     * 设置顶部显示角标
     *
     * @return {@link CornerLabelView}
     */
    public CornerLabelView top() {
        this.mIsTop = true;
        invalidate();
        return this;
    }

    /**
     * 设置底部显示角标
     *
     * @return {@link CornerLabelView}
     */
    public CornerLabelView bottom(BaseImageView test) {
        this.mIsTop = false;
        image3 = test;
        invalidate();
        return this;
    }

    /**
     * 设置角标三角形铺满样式
     *
     * @param value {@code true} 展示 text1、text2, {@code false} 展示 text1
     * @return {@link CornerLabelView}
     */
    public CornerLabelView triangle(boolean value) {
        this.mIsTriangle = value;
        isClickTriangle = true;
        invalidate();
        return this;
    }

    // =========
    // = Text1 =
    // =========

    /**
     * 设置文本
     *
     * @param text 文本
     * @return {@link CornerLabelView}
     */
    public CornerLabelView setText1(String text) {
        mText1.text = text;
        mText1.init();
        postLayout();
        invalidate();
        return this;
    }

    /**
     * 设置字体颜色
     *
     * @param textColor 字体颜色
     * @return {@link CornerLabelView}
     */
    public CornerLabelView setTextColor1(Color textColor) {
        mText1.textColor = textColor;
        mText1.init();
        invalidate();
        return this;
    }

    /**
     * 设置字体高度
     *
     * @param textHeight 字体高度 ( px )
     * @return {@link CornerLabelView}
     */
    public CornerLabelView setTextHeight1(int textHeight) {
        mText1.textHeight = textHeight;
        mText1.init();
        invalidate();
        return this;
    }

    /**
     * 设置字体是否加粗
     *
     * @param textBold {@code true} yes, {@code false} no
     * @return {@link CornerLabelView}
     */
    public CornerLabelView setTextBold1(boolean textBold) {
        mText1.textBold = textBold;
        mText1.init();
        postLayout();
        invalidate();
        return this;
    }

    // =========
    // = Text2 =
    // =========

    /**
     * 设置文本
     *
     * @param text 文本
     * @return {@link CornerLabelView}
     */
    public CornerLabelView setText2(String text) {
        mText2.text = text;
        mText2.init();
        postLayout();
        invalidate();
        return this;
    }

    /**
     * 设置字体颜色
     *
     * @param textColor 字体颜色
     * @return {@link CornerLabelView}
     */
    public CornerLabelView setTextColor2(Color textColor) {
        mText2.textColor = textColor;
        mText2.init();
        invalidate();
        return this;
    }

    /**
     * 设置字体高度
     *
     * @param textHeight 字体高度 ( px )
     * @return {@link CornerLabelView}
     */
    public CornerLabelView setTextHeight2(int textHeight) {
        mText2.textHeight = textHeight;
        mText2.init();
        this.mHeight = (int) (mPaddingTop + mPaddingCenter + mPaddingBottom
                + mText1.textHeight + mText2.textHeight);
        postLayout();
        invalidate();
        return this;
    }

    /**
     * 设置字体是否加粗
     *
     * @param textBold {@code true} yes, {@code false} no
     * @return {@link CornerLabelView}
     */
    public CornerLabelView setTextBold2(boolean textBold) {
        mText2.textBold = textBold;
        mText2.init();
        postLayout();
        invalidate();
        return this;
    }

    // =

    /**
     * 刷新重绘处理
     *
     * @return {@link CornerLabelView}
     */
    public CornerLabelView refresh() {
        mText1.init();
        mText2.init();
        postLayout();
        invalidate();
        return this;
    }

    // =

    /**
     * detail: 画笔
     *
     * @author Ttt
     */
    public static final class Painter {

        private Painter() {
        }

        // 画笔
        private final Paint paint = new Paint();
        // 绘制文本
        private String text = "";
        // 绘制字体颜色
        private Color textColor = Color.WHITE;
        // 字体高度
        private int textHeight = 0;
        // 字体是否加粗
        private boolean textBold = false;
        // 偏移值
        private float offset = 0;

        /**
         * 初始化处理
         */
        void init() {
            paint.setTextAlign(LayoutAlignment.CENTER);
            paint.setColor(textColor);
            paint.setTextSize(textHeight);
            paint.setFakeBoldText(textBold);
            // 计算偏移值
            if (text == null) text = "";
           /* Rect rect = new Rect();
            rect = paint.getTextBounds(text);*/
            offset = textHeight / 2;
            LogUtils.error(TAG, "offset:" + offset);
        }

        /**
         * 绘制处理
         *
         * @param canvas 画布
         * @param y      绘制 Y 轴坐标
         * @param isTop  是否顶部绘制
         */
        void draw1(
                Canvas canvas,
                float y,
                boolean isTop
        ) {
            canvas.drawText(paint, text, textHeight + offset * 2, (isTop ? -1 : 1) * (y + textHeight / 2) + offset);
        }

        /**
         * 绘制处理
         *
         * @param canvas 画布
         * @param y      绘制 Y 轴坐标
         * @param isTop  是否顶部绘制
         */
        void draw2(
                Canvas canvas,
                float y,
                boolean isTop
        ) {
            canvas.drawText(paint, text, textHeight, (isTop ? -1 : 1) * (y + textHeight / 2) + offset);
        }


        // ===============
        // = 对外公开方法 =
        // ===============

        /**
         * 获取画笔
         * <pre>
         *     设置了部分属性样式等, 需调用 {@link #refresh}
         * </pre>
         *
         * @return {@link Paint}
         */
        public Paint getPaint() {
            return paint;
        }

        /**
         * 获取文本
         *
         * @return 文本
         */
        public String getText() {
            return text;
        }

        /**
         * 获取字体颜色
         *
         * @return 字体颜色
         */
        public Color getTextColor() {
            return textColor;
        }

        /**
         * 获取字体高度
         *
         * @return 字体高度 ( px )
         */
        public float getTextHeight() {
            return textHeight;
        }

        /**
         * 获取字体是否加粗
         *
         * @return {@code true} yes, {@code false} no
         */
        public boolean isTextBold() {
            return textBold;
        }
    }

    public void setLeftMargin() {
        setMarginLeft(leftMargin);
        invalidate();
    }

    public void setTopMargin() {
        setMarginTop(topMargin);
    }
}